import {createSlice} from "@reduxjs/toolkit";
import axios from "axios";

const foodsStore = createSlice({
  name: "foods",
  initialState: {
    // 商品列表
    foodsList: [], // 菜单激活下标
    activeIndex: 0, // 购物车列表
    cartList: []
  },
  reducers: {
    // 修改商品列表
    setFoodsList(state, action) {
      state.foodsList = action.payload;
    },

    // 修改activeIndex
    changeActiveIndex(state, action) {
      state.activeIndex = action.payload;
    },

    // 修改carList
    addCar(state, action) {
      const item = state.cartList.find(item => item.id === action.payload.id);
      // 如果有就count++ 没有就直接添加新商品
      if (item) {
        item.count++
      } else {
        state.cartList.push(action.payload)
      }
    }, // count+
    incrCount(state, action) {
      // 关键找到要修改谁的 count
      const item = state.cartList.find(item => item.id === action.payload.id);
      item.count++
    }, // count-
    decrCount(state, action) {
      // 关键找到要修改谁的 count
      const item = state.cartList.find(item => item.id === action.payload.id);
      if (item.count === 0) {

      } else {
        item.count--
      }
    }, // 清除购物车
    clearCart(state) {
      state.cartList = []
    }
  }
})

// 异步请求部分
const {
  clearCart,
  incrCount,
  decrCount,
  setFoodsList,
  changeActiveIndex,
  addCar
} = foodsStore.actions;

const fetchFoodsList = () => {
  return async (dispatch) => {
    const res = await axios.get("http://localhost:3004/takeaway");
    dispatch(setFoodsList(res.data));
  }
}

const foodsReducer = foodsStore.reducer

// 导出action creators
export {clearCart, incrCount, decrCount, fetchFoodsList, changeActiveIndex, addCar}

// 导出生成的slice reducer
export default foodsReducer